#@laybase() 
#define main()
<style>
	.datatable a {
		display: block;
	}
	
	#accountModal .input-group {
		padding: 0px 35px 15px;
	}
	
	#accountModal .input-group.showcls {
		display: block;
	}
	
	#accountModal .input-group.hidecls {
		display: none;
	}
	
	#accountModal .input-group:last-child {
		padding-bottom: 0;
	}
	
	#accountModal .input-group .checkbox-inline {
		color: #333;
	}
	
	#accountModal .modal-footer .readonly {
		display: inline-block;
		text-align: left;
   		width: 80%;
	}
	
	#accountModal .modal-footer .readonly label {
		font-weight: normal;
	}
	
	#accountModal .modal-footer .readonly input {
		vertical-align: top;
	}
	
	p {
		margin: 0;
		line-height: 24px;
	}
</style>
<div class="modal fade" id="accountModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">提示</h4>
      </div>
      <div class="modal-body">
                   
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary confirm">Save changes</button>
      </div>
    </div>
  </div>
</div>
<div class="col-md-12">
	<div id="toolbar" class="btn-group" style="top: 10px">
		<button id="btn_add" type="button" class="btn btn-default" data-toggle='modal' data-target='#accountModal'>
		    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
		</button>
    </div>
	<table class="datatable" id="datatable" data-unique-id="id"></table>
</div>

<script>
	$(function(){
		var dataXml = null,
			$table = $('#datatable'),
			xmls = null,
			powerPositon = {},//权限映射
			operatorArr = ["云网滇盟","嘉腾车贷","温州信聚隆","陕西金知珠","常州万通","杭州嘉业","福建融顺"],//运营商
			optArr = ["苏宁","绿城","铜掌柜","长安","明云"];//通道 
		$.getJSON("/account/userList",function(data){
			console.log(data)
			var newData = data.users
			dataXml = data.xmls;
			xmls = data.xmls
			
			for(var key in dataXml){
				for(var i = 0;i < dataXml[key].length;i++){
					var xmlData = dataXml[key][i],
						json = {}
					json.pageName = xmlData.pageName
					json.positon = xmlData.positon
					powerPositon[xmlData.idx] = json
				}
			}
			
			for(var i = 0;i < newData.length;i++){
				newData[i].id = i;
				newData[i].edit = "<a href='#' data-toggle='modal' data-target='#accountModal'>编辑</a>";
				newData[i].del = "<a href='#' data-toggle='modal' data-target='#accountModal'>删除</a>";
				newData[i].powerList2 = newData[i].powerList
				newData[i].powerList = getPositon(newData[i].powerList)
				if(newData[i].readonly == 0){
					newData[i].readonlyText = "否"
				}else{
					newData[i].readonlyText = "是"
				}
			}
			
			var titles = []
			for(var i = 0;i < data.titles.length;i++){
				var json = {}
				json.field = data.fields[i]
				json.title = data.titles[i]
				if(json.field === "readonly"){
					json.field = "readonlyText"
				}
				if(json.field === "powerList")json.align = "left"
				titles.push(json)
			}
			titles.push({field:"edit",title:"编辑"})
			titles.push({field:"del",title:"删除"})
			
			createTable(titles,newData)
		})
		
		//把权限过滤为中文
		function getPositon(idx){
			if(_x.isEmpty(idx))return ""
			var idxArr = idx.split(","),
				powers = [];
			
			for(var i = 0;i < idxArr.length;i++){
				powers.push(powerPositon[idxArr[i]])
			}
			
			var json = {},
				arr = []
			
			for(var i = 0;i < powers.length;i++){
				arr.push(powers[i].positon)
				if(json[powers[i].positon]){
					var html = json[powers[i].positon].html
					json[powers[i].positon].html = html + "," +powers[i].pageName
				}else{
					json[powers[i].positon] = {
						positon: powers[i].positon,
						html: powers[i].pageName
					}
				}
					
			}
			
			var html = ""
			arr = _x.unique(arr)
			for(var i = 0;i < arr.length;i++){
				if(json[arr[i]]){
					html += "<p>"+ json[arr[i]].positon +"："+ json[arr[i]].html
				}
			}
			
			return html
		}
		
		//创建表格
		function createTable(titles,data){
			$table.bootstrapTable({
				uniqueId: 'id',	
				search: true,
				pagination: true, 
	            pageSize: 10,
	            toolbar: '#toolbar',
				onClickRow: function (row, tr,field) {
					console.log(row)
				    if(field === "edit"){//编辑
				    	editModal(row.account,row.id,row)
				    }else if(field === "del"){//删除
				    	deleteModal(row.account,row.id)
				    }
				},
			    columns: titles,
			    data: data,
			    sortStable:true
			});		
		}
		
		var modalDom = $("#accountModal"),
			modalBody = modalDom.find(".modal-body"),
			modalTitle = modalDom.find(".modal-title"),
			modalConfirm = modalDom.find(".confirm");
		
		modalDom.on("change","#password",function(){
			$(this).parent().addClass("inputyz-hook")
			if(_x.isEmpty($(this).val())){
				$(this).parent().removeClass("inputyz-hook")
			}
		})
		//编辑模态框
		function editModal(account,uniqueId,row){
			modalBody.removeAttr("style")
			modalTitle.html("修改用户")
			modalConfirm.html("保存").addClass("edit").removeClass("delete create").data("account",account).data("uniqueId",uniqueId).data("row",row)
			var rowData = $table.bootstrapTable('getRowByUniqueId',uniqueId),
				html = "",
				powerHtml = "",
				operatorHtml = "",
				optHtml = "",
				optSelArr = []
			
			for(var i = 0;i < operatorArr.length;i++){
				var checked = "checked='true'";
				
				if(!row.operators || row.operators.indexOf(operatorArr[i]) === -1){
					checked = "";
				}
				operatorHtml += "<label class='checkbox-inline' style='margin-left: 10px'>"+
								"    <input type='checkbox' name='operators' value='"+ operatorArr[i] +"' "+ checked +">"+ operatorArr[i] +
								"</label>";
			}
			
			for(var i = 0;i < optArr.length;i++){
				var checked = "checked='true'";
				
				if(_x.isEmpty(row.opts) || row.opts.indexOf(optArr[i]) === -1){
					checked = "";
				}
				
				if(row.opts.indexOf(optArr[i]) != -1){
					optSelArr.push(optArr[i])
				}
				
				optHtml += "<label class='checkbox-inline' style='margin-left: 10px'>"+
						   "    <input type='checkbox' name='opts' class='opts-hook' value='"+ optArr[i] +"' "+ checked +">"+ optArr[i] +
						   "</label>";
			}
			
			for(var key in xmls){
				powerHtml += "<div class='input-group checkboxyz-hook opthideparent-hook noyz hidecls'><span class='input-group-addon' style='border: 1px solid #ccc;border-radius: 4px;'>"+ key +"</span>"
				for(var i = 0;i < xmls[key].length;i++){
					var xmlsData = xmls[key][i]
					powerHtml += "<label class='checkbox-inline opthide-hook' style='display: none;margin-left: 10px' opt='"+ xmlsData.optFilter +"'>"+
								 "    <input type='checkbox' name='powerList' class='opt-hook' value='"+ xmlsData.idx +"'>"+ xmlsData.pageName +
								 "</label>";
				}
				powerHtml += "</div>"
			}
			
			html += "<div class='input-group'>"+
					"	<label class='input-group-addon' for='account'>用户名</label>"+
					"	<input type='text' class='form-control' placeholder='用户名' readonly name='account' id='account' value='"+ rowData.account +"' />"+
					"</div>"+
					"<div class='input-group inputyz-hook'>"+
					"	<label class='input-group-addon' for='name'>姓名</label>"+
					"	<input type='text' class='form-control' placeholder='姓名' name='name' id='name' value='"+ rowData.name +"' />"+
					"</div>"+
					"<div class='input-group inputyz-hook'>"+
					"	<label class='input-group-addon' for='phone'>电话</label>"+
					"	<input type='text' class='form-control' placeholder='电话' name='phone' id='phone' value='"+ rowData.phone +"' />"+
					"</div>"+
					"<div class='input-group'>"+
					"	<label class='input-group-addon' for='password'>密码</label>"+
					"	<input type='text' class='form-control' placeholder='密码' name='password' id='password' />"+
					"</div>"+
					"<div class='input-group checkboxyz-hook noyz'>"+
					"	<span class='input-group-addon' style='border: 1px solid #ccc;border-radius: 4px;'>运营商权限</span>"+
						operatorHtml+
					"</div>"+
					"<div class='input-group checkboxyz-hook optparent-hook noyz'>"+
					"	<span class='input-group-addon' style='border: 1px solid #ccc;border-radius: 4px;'>资金通道权限</span>"+
						optHtml+
					"</div>" + powerHtml;
					
			modalBody.removeClass("has-error").html(html).css({"max-height":$(window).height() * 0.78,"overflow":"auto"})
			if(optSelArr.length > 0)getPosition(optSelArr,row.powerList2.split(","))
			var checked = "checked='checked'"
			if(row.readonly == 0){
				checked = ""
			}
			modalBody.siblings(".modal-footer").children(".readonly").remove()
			$("<div class='readonly'><label><input type='checkbox' "+ checked +" class='readonly-hook' name='readonly'>&nbsp;观察者用户</label></div>").insertBefore(modalBody.siblings(".modal-footer").children(".btn-default"))
		}
		
		//编辑提交
		modalDom.on("click","button.edit",function(){
			var data = yzInput(),
				readonlyDom = modalDom.find(".readonly-hook")
			if(readonlyDom.prop("checked")){
				data.readonly = 1
				data.readonlyText = "是"
			}else{
				data.readonly = 0
				data.readonlyText = "否"
			}
			if(data.mark){
				data.account = $(this).data("account")
				var row = $(this).data("row")
				row.name = data.name;
				row.powerList2 = data.powerList
				row.powerList = getPositon(data.powerList);
				row.operators = data.operators;
				row.opts = data.opts;
				row.phone = data.phone,
				row.password = data.password;
				row.readonly = data.readonly;
				row.readonlyText = data.readonlyText;
				$table.bootstrapTable('updateRow', {row:row});
				axios.post("/account/fix",_x.qsStringify(data))
				.then(function(res){
					if(res.data.code == 1){
						_x.show_alert_sh(res.data.msg,true,300)
					}else{
						_x.show_alert_sh("保存失败！",false,300)
					}
					modalDom.modal('hide')
				})
			}
		})
		
		//焦点验证
		modalBody.on("blur",".inputyz-hook input",function(){
			inputBlur($(this))
		})
		
		//删除模态框
		function deleteModal(account,uniqueId){
			var delHtml = "<input type='text' class='del-hook form-control' placeholder='请输入要删除账号的用户名' style='width: 50%;margin: 34px auto 0;' />";
			modalBody.css({"padding":"40px 5px","font-size":"22px","text-align":"center"}).html("您真的要删除吗？" + delHtml)
			modalTitle.html("删除用户")
			modalBody.siblings(".modal-footer").children(".readonly").remove()
			modalConfirm.html("确定").addClass("delete").removeClass("edit create").data("account",account).data("uniqueId",uniqueId)
		}
		
		//删除
		modalDom.on("click","button.delete",function(){
			var account = $(this).data("account"),
				uniqueId = $(this).data("uniqueId");
			if(!_x.isEmpty(account) && !_x.isEmpty(uniqueId)){
				var delInput = $(this).parents(".modal-content").find("input.del-hook")
				if(account != delInput.val()){
					delInput.val("").attr("placeholder","用户名错误！").parent().addClass("has-error")
				}else{
					delInput.parent().removeClass("has-error")
					axios.post("/account/deleteUser",_x.qsStringify({account:account}))
					.then(function(res){
						if(res.data.code == 1){
							$table.bootstrapTable('removeByUniqueId', uniqueId);
							_x.show_alert_sh(res.data.msg,true,300)
						}else{
							_x.show_alert_sh(res.data.msg,false,300)
						}
						modalDom.modal('hide')
					})
				}
			}
		})
		
		//验证
		function yzInput(){
			var data = {
					mark: true,
					powerList: "",
					operators: "",
					opts: ""
				},
				flag = true;
			modalBody.find(".input-group").each(function(){
				var that = $(this);
				if(that.hasClass("inputyz-hook")){
					var input = that.children("input"),
						val = input.val();
					if(_x.isEmpty(val)){
						that.addClass("has-error")
						data.mark = false;
					}else{
						if(!_x.isEmpty(input.attr("c-name"))){
							data[input.attr("c-name")] = val;
						}else{
							data[input.attr("name")] = val;
						}
					}
				}else if(that.hasClass("checkboxyz-hook")){
					if(that.hasClass("hidecls"))return true
					that.find("input").each(function(){
						if($(this).hasClass("opt-hook")){
							if($(this).prop("checked") === true){
								data.powerList += $(this).val() + ","
							}
						}else{
							if($(this).prop("checked")){
								data[$(this).attr("name")] = ""
								that.find("input").each(function(){
									if($(this).prop("checked") === true){
										data[$(this).attr("name")] += $(this).val() + ",";
									}
								})
								if(!that.hasClass("noyz")){
									that.removeClass("has-error")
									flag = true
									return false
								}
							}else{
								if(!that.hasClass("noyz")){
									that.addClass("has-error")
									flag = false;
								}
							}
						}
					})
				}
			})
			if(data.mark && flag){
				data.mark = true;
				if(data.powerList)data.powerList = data.powerList.substring(0,data.powerList.length - 1)
				if(data.operators){
					data.operators = data.operators.substring(0,data.operators.length - 1)
				}else{
					data.operators = ""
				}
				if(data.opts){
					data.opts = data.opts.substring(0,data.opts.length - 1)
				}else{
					data.opts = ""
				}
			}else{
				data.mark = false;
			}
			return data
		}
		
		//焦点验证
		function inputBlur(input){
			var val = input.val();
			if(_x.isEmpty(val)){
				input.parent().addClass("has-error");
			}else{
				input.parent().removeClass("has-error");
			}
		}
		
		//新增模态框
		function createModal(){
			modalBody.removeAttr("style")
			modalTitle.html("创建用户")
			modalConfirm.html("提交").addClass("create").removeClass("delete edit")
			var html = "",
				powerHtml = "";
			for(var key in xmls){
				powerHtml += "<div class='input-group checkboxyz-hook opthideparent-hook noyz hidecls'><span class='input-group-addon' style='border: 1px solid #ccc;border-radius: 4px;'>"+ key +"</span>"
				for(var i = 0;i < xmls[key].length;i++){
					var xmlsData = xmls[key][i]
					powerHtml += "<label class='checkbox-inline opthide-hook' style='display: none;margin-left: 10px' opt='"+ xmlsData.optFilter +"'>"+
								 "    <input type='checkbox' name='powerList' class='opt-hook' value='"+ xmlsData.idx +"'>"+ xmlsData.pageName +
								 "</label>";
				}
				powerHtml += "</div>"
			}
			var operatorHtml = "",
				optHtml = "";
			for(var i = 0;i < operatorArr.length;i++){
				operatorHtml += "<label class='checkbox-inline' style='margin-left: 10px'>"+
								"    <input type='checkbox' name='operators' value='"+ operatorArr[i] +"'>"+ operatorArr[i] +
								"</label>";
			}
			
			for(var i = 0;i < optArr.length;i++){
				optHtml += "<label class='checkbox-inline' style='margin-left: 10px'>"+
						   "    <input type='checkbox' name='opts' class='opts-hook' value='"+ optArr[i] +"'>"+ optArr[i] +
						   "</label>";
			}
			html += "<div class='input-group inputyz-hook'>"+
					"	<label class='input-group-addon' for='account'>用户名</label>"+
					"	<input type='text' class='form-control' placeholder='用户名' c-name='account' id='account' autocomplete='off' />"+
					"</div>"+
					"<div class='input-group inputyz-hook'>"+
					"	<label class='input-group-addon' for='name'>姓名</label>"+
					"	<input type='text' class='form-control' placeholder='姓名' c-name='name' autocomplete='off' />"+
					"</div>"+
					"<div class='input-group inputyz-hook'>"+
					"	<label class='input-group-addon' for='phone'>电话</label>"+
					"	<input type='text' class='form-control' placeholder='电话' name='phone' id='phone' autocomplete='off' />"+
					"</div>"+
					"<div class='input-group inputyz-hook'>"+
					"	<label class='input-group-addon' for='password'>密码</label>"+
					"	<input type='text' class='form-control' placeholder='密码' c-name='password' id='password' autocomplete='off' />"+
					"</div>"+
					"<div class='input-group checkboxyz-hook noyz'>"+
					"	<span class='input-group-addon' style='border: 1px solid #ccc;border-radius: 4px;'>运营商权限</span>"+
					operatorHtml+
					"</div>"+
					"<div class='input-group checkboxyz-hook optparent-hook noyz'>"+
					"	<span class='input-group-addon' style='border: 1px solid #ccc;border-radius: 4px;'>资金通道权限</span>"+
					optHtml+
					"</div>" +　powerHtml;
					
			modalBody.removeClass("has-error").html(html).css({"max-height":$(window).height() * 0.78,"overflow":"auto"})
			modalBody.siblings(".modal-footer").children(".readonly").remove()
			$("<div class='readonly'><label><input type='checkbox' class='readonly-hook' name='readonly'>&nbsp;观察者用户</label></div>").insertBefore(modalBody.siblings(".modal-footer").children(".btn-default"))
		}
		
		//新建--过滤岗位
		modalBody.on("change","input.opts-hook",function(){
			var optArr = [],
				inputs = $(this).parents(".optparent-hook").find("input.opts-hook")
			inputs.each(function(){
				if($(this).prop("checked")){
					optArr.push($(this).val())
				}
			})
			
			if(optArr.length === 0){
				modalBody.find(".opthideparent-hook").addClass("hidecls")
				modalBody.find(".opthide-hook").hide()
				return
			}
			
			getPosition(optArr)
			
		})
		
		function getPosition(optArr,powerArr){
			var optLen = optArr.length
				
			modalBody.find(".opthideparent-hook").each(function(){
				var mark = false
				$(this).find(".opthide-hook").each(function(){
					var opts = $(this).attr("opt")
					for(var i = 0;i < optLen;i++){
						if(opts.indexOf(optArr[i]) != -1){
							mark = true
							$(this).show()
							break
						}
					}
				})
				if(mark){
					$(this).removeClass("hidecls")
				}else{
					$(this).addClass("hidecls")
				}
			})
			
			if(powerArr){
				for(var i = 0;i < powerArr.length;i++){
					modalBody.find("input[value='"+ powerArr[i] +"']").prop("checked",true)
				}
			}
		}
		
		//新增按钮
		$("#btn_add").click(function(){
			createModal()
		})
		
		//创建提交
		modalDom.on("click","button.create",function(){
			var data = yzInput(),
				readonlyDom = modalDom.find(".readonly-hook")
			if(readonlyDom.prop("checked")){
				data.readonly = 1
				data.readonlyText = "是"
			}else{
				data.readonly = 0
				data.readonlyText = "否"
			}
			getPositon(data.powerList)
			
			if(data.mark){
				axios.post("/account/createUser",_x.qsStringify(data))
				.then(function(res){
					if(res.data.code == 1){
						var date = new Date(),
							year = date.getFullYear(),
							month = date.getMonth() + 1,
							day = date.getDate(),
							hours = date.getHours(),
							minutes = date.getMinutes(),
							seconds = date.getSeconds();
						if(month < 10)month = "0" + month
						if(day < 10)day = "0" + day
						if(hours < 10)hours = "0" + hours
						if(minutes < 10)minutes = "0" + minutes
						if(seconds < 10)seconds = "0" + seconds
						_x.show_alert_sh(res.data.msg,true,300)
						modalDom.modal('hide')
						var newData = {
							account: data.account,
							del: "<a href='#' data-toggle='modal' data-target='#accountModal'>删除</a>",
							edit: "<a href='#' data-toggle='modal' data-target='#accountModal'>编辑</a>",
							id: date.getTime(),
							name: data.name,
							phone: data.phone,
							powerList2: data.powerList,
							powerList: getPositon(data.powerList),
							operators: data.operators,
							opts: data.opts,
							readonly: data.readonly,
							readonlyText: data.readonlyText,
							regTime: year +"-"+ month +"-"+ day +" "+ hours +":"+ minutes +":"+ seconds 
						}
						$table.bootstrapTable('prepend', newData);
					}else{
						_x.show_alert_sh(res.data.msg,false,300)
						if(res.data.msg == "该用户名已注册！"){
							$("#account").parent().addClass("has-error")
						}
					}
				})
			}
		})
		
	})
</script>
#end
